/**
 * Created by user on 2015/9/23.
 */

angular.module('mis.marketManager.controllers', []).
    controller('secondHandCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {


        $scope.currentPage = 1;
        $scope.pageSize = 15;

        $scope.categoryList = [];
        //$scope.categoryServicesList = [];
        $scope.itemTypeWord = {1:"闲置", 2:"服务"};

        $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/market/getGoodsCategory', {},{
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (result) {
            $scope.categoryList = result.data;
            //var lenn = result.data.length;
            //for(var i =0; i<lenn;++i){
            //    var _g = result.data[i];
            //    if (_g.itemType == 2) {
            //        $scope.categoryServicesList.push(_g);
            //    } else {
            //        $scope.categoryList.push(_g);
            //    }
            //}
        }).error(function () {
        });

        $scope.dealStatusList = [
            {value: '0',name:'未交易'},
            {value: '1',name:'已交易'}
        ];

        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/market/secondHandList/:page/:size',
            ajax: $http,
            success:function(data){
                //console.debug(data.data.list);
                if(data && data.data) {
                    $scope.goodsList = data.data.list;
                    $scope.pageNumber = data.data.totalPage;
                    $scope.count = data.data.count;
                    $scope.pagination.totalPage = data.data.totalPage;
                }
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){
                $scope.goodsList = null;
            },
            params: {}
        });

        //搜索
        $scope.search = function (temp) {
            var current = temp.target;

            if (current) {
                $scope.currentPage = $scope.pagination.currentPage;
            }else {
                $scope.pagination.currentPage = 1;
                $scope.currentPage = 1;
            }

            var city = $scope.cascading.getCity(document.getElementById("search-target"));
            var community = $scope.cascading.getVillageId(document.getElementById("search-target"));
            var body = {};

            if (city) body.city = city;
            if (community) body.community = community;
            if ($scope.createdBy) body.createdBy = $scope.createdBy;
            if ($scope.nickName) body.nickName = $scope.nickName;
            if ($scope.phone) body.phone = $scope.phone;
            if ($scope.category != '') body.category = $scope.category;
            if ($scope.dealStatus != '') body.dealStatus = $scope.dealStatus;
            if ($scope.title) body.title = $scope.title;
            if ($scope.floorPrice) body.floorPrice = $scope.floorPrice;
            if ($scope.topPrice) body.topPrice = $scope.topPrice;
            if ($scope.level) body.level = $scope.level;
            if ($scope.sale) body.sale = $scope.sale;
            if ($scope.itemType) body.itemType = $scope.itemType;

            if ($("#startDate").val()) body.startDate = $("#startDate").val() + ' 00:00:00';
            if ($("#endDate").val()) body.endDate = $("#endDate").val() + ' 23:59:59';
            if (body.startDate && body.endDate && body.startDate > body.endDate) {
                alert('开始日期不能大于结束日期');
                return;
            }
            if ($scope.sort) body.sort = $scope.sort;

            console.log(body)

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/market/secondHandList/' + $scope.currentPage + '/' + $scope.pageSize, body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if(data && data.data) {
                    $scope.goodsList = data.data.list;
                    $scope.pageNumber = data.data.totalPage;
                    $scope.count = data.data.count;
                    $scope.pagination.totalPage = data.data.totalPage;
                }
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = body;
            }).error(function (err) {
                $scope.goodsList = null;
                alert(err);
            });
        };

        //全选列表
        $scope.allSelected = function(){
            $scope.pagination.allSelected();
        };

        //删除
        $scope.delete = function(){
            var params = {
                url: 'http://' + backOfficeHost + '/rest/v1.0/mis/market/deleteSecondHand',
                checkObj: $(".item-check"),//checkbox对象
                key: "secondHandID",
                success: function(data){
                    //var number = $(".am-active").text();//当前页码
                    $scope.search(true);
                    alert("删除成功！");
                },
                error: function(){}
            };
            $scope.pagination.listDelete(params);
        };

        $scope.secondHandEdit = function(secondHand){

            $scope.updateData = secondHand;
            $('#dealStatus').val(secondHand.dealStatus);
            $('#type').val(secondHand.type);
            //for(img in secondHand.images){
            //    $scope.updateData.images[img].imageURL = 'http://'+ imgHost + secondHand.images[img].imageURL;
            //};

            //updateData.images.forEach(function(img){
            //
            //    img.imageURL = imgHost+img.imageURL;
            //});

            //$scope.updateData.dealStatuss = secondHand.dealStatus.toString();
            //$scope.updateData.descs = secondHand.desc;
            //$scope.url = banner.url;

            //$scope.cascading.paint($("#cascad-edit")[0],false, 'edit');

            //document.getElementById('begin').valueAsDate  = new Date(banner.beginDate);
            //document.getElementById('end').valueAsDate  = new Date(banner.endDate);
            //
            ////$scope.cascading.paint($("#cascad-edit")[0],false);
            //$("#cascad-edit").find(".c-provinces").val(banner.province.name);
            //if(banner.province)$("#cascad-edit").find(".c-provinces")[0].dataset.cId = banner.province.objId;
            //
            //$("#cascad-edit").find(".c-citys").val(banner.city.name);
            //if(banner.city)$("#cascad-edit").find(".c-citys")[0].dataset.cId = banner.city.objId;
            //
            //$("#cascad-edit").find(".c-cityArea").val(banner.county.name);
            //if(banner.county)$("#cascad-edit").find(".c-cityArea")[0].dataset.cId = banner.county.objId;
            //
            //if(banner.community)$('#selCommunitys').val(banner.community);

            console.debug($scope.updateData);

            $('#doc-modal-edit').modal({target: '#doc-modal-edit', width: 700, height: 690 });
        };


        $scope.updateSecondHand = function(updateData) {

            if (!updateData.title) {
                alert('标题不能为空!'); return;
            };
            if (!updateData.desc) {
                alert('描述不能为空!'); return;
            };
            if (updateData.type ==2 && updateData.presentPrice>0) {
                alert('免费物品现价不能大于0'); return;
            };

            var uData = {id:updateData.objId, secondHand:{}};
            //if(updateData.objId)uData.secondHandID = updateData.objId;
            if(updateData.title != null)uData.secondHand.title = updateData.title;
            if(updateData.desc != null)uData.secondHand.desc = updateData.desc;
            if(updateData.type != null)uData.secondHand.type = updateData.type;
            if(updateData.category){
                var categoryId = updateData.category.objId;
                uData.secondHand.category = categoryId;
                for(var i = 0, lenn = $scope.categoryList.length; i < lenn; ++i){
                    var _cat = $scope.categoryList[i];
                    if (_cat.objId == categoryId) {
                        uData.secondHand.itemType = _cat.itemType;
                        break;
                    }
                }
            }
            if(updateData.presentPrice != null)uData.secondHand.presentPrice = updateData.presentPrice;
            if(updateData.originalPrice != null)uData.secondHand.originalPrice = updateData.originalPrice;
            if($('#dealStatus option:selected').val())uData.secondHand.dealStatus = $('#dealStatus option:selected').val();

            console.log(uData);

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/market/updateSecondHand', uData, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                //var pageNumber = $(".am-active").text();//当前页码
                if (data.result.status == 1) {
                    $('#doc-modal-edit').modal("close");
                    //$scope.pagination.selectPage(pageNumber);
                    $scope.search(true);
                    alert('修改成功!');
                }else {
                    alert('修改失败!');
                }
            }).error(function (err) {
                //var number = $(".am-active").text();//当前页码
                $('#doc-modal-edit').modal("close");
                alert("修改失败！");
            });

        };


        //查看回复数
        $scope.replieCount = function(goods){

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/market/getReplyList', {goodsId : goods.objId}, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if(data.data && data.data.length>0) {
                    $scope.replyList = data.data;
                    console.debug(data.data);

                    for(img in data.data[0].goodsId.images) {
                        data.data[0].goodsId.images[img].imageURL = 'http://' + imgHost + data.data[0].goodsId.images[img].imageURL;
                    };
                    $scope.repGoods = [];
                    $scope.repGoods = data.data[0].goodsId.images;
                }else{
                    $scope.replyList ={};
                    $scope.repGoods = [];
                    //for(img in goods.images) {
                    //    if(goods.images[img].imageURL.indexOf('http://')  == -1) {
                    //        goods.images[img].imageURL = 'http://' + imgHost + goods.images[img].imageURL;
                    //    }
                    //};
                    $scope.repGoods =goods.images;
                }

                $('#doc-modal-reply').modal({target: '#doc-modal-reply', width: 700, height: 690});


            }).error(function (err) {
                alert(err);
            });

        }


        $scope.exportGoods = function (current) {


            var href = 'http://' + backOfficeHost + '/rest/v1.0/mis/market/exportSecondHand/?isValid=true';

            var city = $scope.cascading.getCity(document.getElementById("search-target"));
            var community = $scope.cascading.getVillageId(document.getElementById("search-target"));
            var body = {};

            if (city) href += "&city="+ city;
            if (community)  href += "&community="+ community;
            if ($scope.createdBy) href += "&createdBy="+ $scope.createdBy;
            if ($scope.nickName) href += "&nickName="+ $scope.nickName;
            if ($scope.phone) href += "&phone=" + $scope.phone;
            if ($scope.category) href += "&category=" + $scope.category;
            if ($scope.dealStatus) href += "&dealStatus=" +$scope.dealStatus;
            if ($scope.title) href += "&title=" +$scope.title;
            if ($scope.level) href += "&level=" +$scope.level;
            if ($scope.floorPrice) href += "&floorPrice=" + $scope.floorPrice;
            if ($scope.topPrice) href += "&topPrice=" + $scope.topPrice;
            if ($scope.sort) href += "&sort=" + $scope.sort;
            //if ($scope.desc) body.desc = $scope.desc;
            //if ($scope.sort) body.sort = $scope.sort;
            if ($scope.sale)  href += "&sale=" + $scope.sale;

            if ($("#startDate").val())  href += "&startDate=" + $("#startDate").val() + ' 00:00:00';
            if ($("#endDate").val())  href += "&endDate=" + $("#endDate").val() + ' 23:59:59';

            if ($("#startDate").val() && $("#endDate").val() && $("#startDate").val() >$("#endDate").val()) {
                alert('开始日期不能大于结束日期');
                return;
            };

            if(!$("#startDate").val() && !$("#endDate").val()){
                alert('请选择发布日期');
                return;
            }

            location.href = href;

        };


        $scope.handleLevel = function (goods,level){

            var opt ={
                id : goods.objId,
                level : level
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/market/handleLevel', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                //var pageNumber = $(".am-active").text();//当前页码
                if (data.result.status == 1) {
                    $('#doc-modal-edit').modal("close");
                    //$scope.pagination.selectPage(pageNumber);
                    $scope.search(true);
                    alert('修改成功!');
                }else {
                    alert('修改失败!');
                }
            }).error(function (err) {
                //var number = $(".am-active").text();//当前页码
                $('#doc-modal-edit').modal("close");
                alert("修改失败！");
            });

        };

        //取消闪购
        $scope.handleSale = function (goods){

            var opt ={
                id : goods.objId
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/market/handleSale', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                //var pageNumber = $(".am-active").text();//当前页码
                if (data.result.status == 1) {
                    //$('#doc-modal-edit').modal("close");
                    //$scope.pagination.selectPage(pageNumber);
                    $scope.search(true);
                    alert('取消闪购成功!');
                }else {
                    alert('取消闪购失败!');
                }
            }).error(function (err) {
                //var number = $(".am-active").text();//当前页码
                //$('#doc-modal-edit').modal("close");
                alert("取消闪购失败！");
            });

        };


        //级联框
        var cascadData = {
            provinceUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionPrivince',
            cityUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCity',
            cityAreaUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCounty',
            villageUrl: 'http://' + backOfficeHost + '/rest/v1.0/mis/community/communityList',
            ajax: $http
        };
        $scope.cascading = new gObj.cascading(cascadData);
        $scope.cascading.paint($(".city-cascading")[0],true);

    }]).controller('secondHandReplyList', ['$scope', '$http', '$location', function ($scope, $http, $location) {

        $scope.currentPage = 1;
        $scope.pageSize = 15;


        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/market/secondHandReplyList/:page/:size',
            ajax: $http,
            success:function(data){
            if(data && data.data) {
                $scope.resultList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.pagination.totalPage = data.data.totalPage;
            }
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){

            },
            params: {}
        });

        $scope.search = function(temp) {

            var current = temp.target;
            if (current) {
                $scope.currentPage = $scope.pagination.currentPage;
            }else {
                $scope.pagination.currentPage = 1;
                $scope.currentPage = 1;
            }

            var body = {};
            if ($scope.replyBy) body.replyBy = $scope.replyBy;
            if ($scope.replyDesc) body.replyDesc = $scope.replyDesc;

            if(!body.replyBy){
                alert('请输入回复者ID');
                $('#loading').modal("close");
                return;
            }

            $('#loading').modal({target: '#loading'});

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/market/secondHandReplyList/' + $scope.currentPage + '/' + $scope.pageSize, body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                //console.debug(data);

                if(data && data.data) {
                    $scope.resultList = data.data.list;
                    $scope.pageNumber = data.data.totalPage;
                    $scope.count = data.data.count;
                    $scope.pagination.totalPage = data.data.totalPage;
                }
                $('#loading').modal("close");
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = body;
            }).error(function (err) {
                $('#loading').modal("close");
                $scope.resultList = null;
            });
        };

        $scope.deleteSecondHandReply = function(reply,index) {

            var opt ={
                goodsId:reply.goodsId,
                replyId:reply.objId,
                replyBy:reply.repliedBy.objId
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/market/deleteSecondHandReply',opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.result.status == 1) {
                    $('#delete-confirm-'+index).modal("close");
                    $scope.search(true);
                }else {
                    alert('删除失败');
                }
            }).error(function () {

            });

        };

    }])
